package com.chenyu.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.chenyu.properties.AlicloudOSSProperties;
import com.chenyu.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 晴
 * @version 1.0
 * @description:
 * @date 2024/6/17 17:12
 */
@RestController
@RequestMapping("/oss")
@Api(tags = "OSSController")
public class OSSController {

    @Autowired
    private AlicloudOSSProperties alicloudOSSProperties;

    @GetMapping("/sign")
    @ApiOperation("oss验证")
    public AjaxResult doGet(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult ajaxResult = new AjaxResult();
        // Endpoint以华东1（杭州）为例，其他Region请按实际情况填写。
        String endpoint = alicloudOSSProperties.getEndpoint();
        // 填写Bucket名称，例如examplebucket。
        String bucket = alicloudOSSProperties.getBucketName();
        // 填写Host名称，格式为https://bucketname.endpoint。
        String host = "https://" + bucket + "." + endpoint;
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String dir = "images";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                endpoint,
                alicloudOSSProperties.getAccessKey(),
                alicloudOSSProperties.getSecretKey()
        );
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", alicloudOSSProperties.getAccessKey());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
            ajaxResult.setData(respMap);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("请求错误！！！");
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

        return ajaxResult;
    }

    @DeleteMapping
    @ApiOperation("oss删除")
    public AjaxResult delete(@RequestParam String fileName) {
        AjaxResult ajaxResult = new AjaxResult();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = alicloudOSSProperties.getEndpoint();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = alicloudOSSProperties.getBucketName();
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        //https://ba-wms-chenyu.oss-cn-chengdu.aliyuncs.com/images/b7747260-dad5-4dad-84a7-bb1b3815f6e0_null-1f0aa0463fd322d8.jpg
        String objectName ="images/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, alicloudOSSProperties.getAccessKey(), alicloudOSSProperties.getSecretKey());
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
            ajaxResult.setMsg("删除成功！！！");
        } catch (OSSException oe) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg(oe.getErrorMessage());
        } catch (ClientException ce) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg(ce.getErrorMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ajaxResult;
    }


}
